package com.J.OpenGLSample;

import static android.opengl.GLES10.*;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class QuadRenderer implements GLSurfaceView.Renderer, OnTouchListener, SensorEventListener {


    public QuadRenderer(Context context) {
        mContext = context;
        mRect1 = new Polygon(0,0,0);
//        angle = 0.0f;
        pXLookAt = 0;
        pYLookAt = 0;
        
    }

    public boolean onTouch(View v, MotionEvent event){
    	if(event.getAction() == MotionEvent.ACTION_MOVE){
//    		if(event.getHistoricalX(0)< event.getX()) pXLookAt += .1;
//    		if(event.getHistoricalX(0)> event.getX()) pXLookAt -= .1;
    		if(event.getHistoricalY(0)< event.getY()) pYLookAt += .1;
    		if(event.getHistoricalY(0)> event.getY()) pYLookAt -= .1;
    	}

    	return true;
    }
    
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    	//Do nothing
    }
    
    public void onSensorChanged(SensorEvent event) {
//        final int type = event.sensor.getType();
//        if(type == Sensor.TYPE_ORIENTATION ){
//        	if(event.values[0] > 0) pXLookAt += .2;
//    		if(event.values[0] < 0) pXLookAt -= .2;
//    		if(event.values[1] > 0) pYLookAt += .2;
//    		if(event.values[1] < 0) pYLookAt -= .2;
        	pXLookAt = event.values[1]/20;
//        	if(pXLookAt > 3){ pXLookAt = 3;}
//        	if(pXLookAt < 3) {pXLookAt = -3;}
//        	pXLookAt += event.values[0]/5;
//        }
    }
    
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        glDisable(GL_DITHER);

        /*
         * Some one-time OpenGL initialization can be made here
         * probably based on features of this particular context
         */
        glHint(GL_PERSPECTIVE_CORRECTION_HINT,
                GL_FASTEST);

        glClearColor(.5f, .5f, .5f, 1);
        glShadeModel(GL_SMOOTH);
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);

        /*
         * Create our texture. This has to be done each time the
         * surface is created.
         */

        
        glGenTextures(3, textures, 0);
        Log.i("***","TTT");
        
        setTexToTexureID(textures[0],R.drawable.sohn);
        setTexToTexureID(textures[1],R.drawable.orange);
        setTexToTexureID(textures[2],R.drawable.l2);
        
    }

	private void setTexToTexureID(int texID, int resourceID) {
		glBindTexture(GL_TEXTURE_2D, texID);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D,
                GL_TEXTURE_MAG_FILTER,
                GL_LINEAR);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
        		GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
        		GL_CLAMP_TO_EDGE);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
                GL_REPLACE);
        Bitmap bitmap;        
        
        bitmap = bitmapGenerator(resourceID);

        GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
        bitmap.recycle();
	}

	private Bitmap bitmapGenerator(int id) {
		Bitmap bitmap;
		InputStream is = mContext.getResources()
                .openRawResource(id);
        try {
        	bitmap = BitmapFactory.decodeStream(is);
        } finally {
            try {
                is.close();
            } catch(IOException e) {
            	Log.i("Exception", "IOException has been occured");
            }
        }
		return bitmap;
	}

    public void onDrawFrame(GL10 gl) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        glDisable(GL_DITHER);

        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
                GL_MODULATE);

        /*
         * Usually, the first thing one might want to do is to clear
         * the screen. The most efficient way of doing this is to use
         * glClear().
         */

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        /*
         * Now we're ready to draw some 3D objects
         */

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        GLU.gluLookAt(gl, pXLookAt, pYLookAt, -4f, 0f, 0f, 0f, 0f, -1.0f, 0.0f);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[1]);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
                GL_REPEAT);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
                GL_REPEAT);

//        glRotatef(0, 0, 0, 1.0f);
        glTranslatef(-1.5f,-.5f,0);
        
        mRect1.draw(gl);

        glTranslatef(.5f,0,-.4f);
        glBindTexture(GL_TEXTURE_2D, textures[2]);
        mRect1.draw(gl);

        glTranslatef(.5f,0,-.4f);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        mRect1.draw(gl);

        
    }

    public void onSurfaceChanged(GL10 gl, int w, int h) {
        glViewport(0, 0, w, h);

        /*
        * Set our projection matrix. This doesn't have to be done
        * each time we draw, but usually a new projection needs to
        * be set when the viewport is resized.
        */

        float ratio = (float) w / h;
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glFrustumf(-ratio,ratio, -1, 1, 3, 25);
    }

    private Context mContext;
    private Polygon mRect1;
//    private float angle;
    private float pXLookAt, pYLookAt;
    private int[] textures = new int[3];

    static class Polygon {
        public Polygon(float x, float y, float z) {

            // Buffers to be passed to gl*Pointer() functions
            // must be direct, i.e., they must be placed on the
            // native heap where the garbage collector cannot
            // move them.
            //
            // Buffers with multi-byte datatypes (e.g., short, int, float)
            // must have their byte order set to native order

            ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
            vbb.order(ByteOrder.nativeOrder());
            mFVertexBuffer = vbb.asFloatBuffer();

            ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
            tbb.order(ByteOrder.nativeOrder());
            mTexBuffer = tbb.asFloatBuffer();

            ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2);
            ibb.order(ByteOrder.nativeOrder());
            mIndexBuffer = ibb.asShortBuffer();
            
          float[] coords = {
	          // X, Y, Z
        		  1.0f+x, 1.0f+y, 0f+z,
        		  0.0f+x, 1.0f+y, 0f+z,
        		  0.0f+x, 0.0f+y, 0f+z,
        		  1.0f+x, 0.0f+y, 0f+z
        		  };

            for (int i = 0; i < VERTS; i++) {
                for(int j = 0; j < 3; j++) {
                    mFVertexBuffer.put(coords[i*3+j]);
                }
            }

            for (int i = 0; i < VERTS; i++) {
                for(int j = 0; j < 2; j++) {
                    mTexBuffer.put(coords[i*3+j]);//+ 0.5f
                }
            }

            for(int i = 0; i < VERTS; i++) {
                mIndexBuffer.put((short) i);
            }

            mFVertexBuffer.position(0);
            mTexBuffer.position(0);
            mIndexBuffer.position(0);
        }

        public void draw(GL10 gl) {
            glFrontFace(GL_CCW);
            glVertexPointer(3, GL_FLOAT, 0, mFVertexBuffer);
            glEnable(GL_TEXTURE_2D);
            glTexCoordPointer(2, GL_FLOAT, 0, mTexBuffer);
            glDrawElements(GL_TRIANGLE_FAN, VERTS,
                    GL_UNSIGNED_SHORT, mIndexBuffer);
        }


        
        private final static int VERTS =4;

        private FloatBuffer mFVertexBuffer;
        private FloatBuffer mTexBuffer;
        private ShortBuffer mIndexBuffer;

    }
}
